﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.ServiceModel.Syndication;
using Common.Library;
using Facebook;
using TweetSharp;
using System.ComponentModel;
using System.Threading;
using System.Collections.ObjectModel;

namespace Social_Celebrities
{
    public class DataItems
    {
        public object item
        {
            get;
            set;
        }
        public object comments
        {
            get;
            set;
        }
    }
    public partial class feedPage : PhoneApplicationPage
    {
        public AutoResetEvent auto = new AutoResetEvent(false);
        List<DataItems> DataSource = new List<DataItems>();
        string BlogComment = string.Empty;
        public string FeedType = string.Empty;
        public object CommentBox = default(object);
        public feedPage()
        {
            InitializeComponent(); 
            Loaded += feedPage_Loaded;
            
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            NavigationContext.QueryString.TryGetValue("FeedType", out FeedType);
        }
        void feedPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (FeedType == "FaceBook")
            {
               
                DataItems d = new DataItems();
                FaceListBox.Visibility = Visibility.Visible;
                d.item=(SyndicationItem)Constants.SelectedSyndicationItem[0];
                if (((ObservableCollection<commentsclass>)Constants.SelectedSyndicationItem[1]).Count == 0)
                    d.comments = null;
                else
                d.comments = (ObservableCollection<commentsclass>)Constants.SelectedSyndicationItem[1];
                DataSource.Add(d);
                FaceListBox.ItemsSource = DataSource;
                string Link = ((SyndicationItem)d.item).Links.FirstOrDefault().Uri.ToString();
               
            }
            else if (FeedType == "Twitter")
            {
                ObservableCollection<TwitterStatus> TwitterComments = new ObservableCollection<TwitterStatus>();
                DataItems d = new DataItems();
                TweetListBox.Visibility = Visibility.Visible;
                d.item=(TwitterStatus)Constants.SelectedSyndicationItem[0];
                TwitterLoginPage p = new TwitterLoginPage();
                var service = new TwitterService("LYTy3T8P556GxqRymimhwA", "5TSKipEjESOAcdBsViWm2E1RVxFEN1Ooh0nRwIj7RsY");
                string[] Tokens = new string[2];
                Tokens = p.ReturnTokens(p.getAccessToken());
                service.AuthenticateWith(Tokens[0], Tokens[1]);
                service.Retweets(new RetweetsOptions() { Id = ((TwitterStatus)d.item).Id }, (ts1, rep1) =>
                {
                    if (rep1.StatusCode == HttpStatusCode.OK)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                               {
                                   foreach (TwitterStatus si1 in ts1)
                                   {
                                       TwitterComments.Add(si1);
                                   }
                                   if (TwitterComments.Count == 0)
                                       d.comments = null;
                                   else
                                   d.comments = TwitterComments;
                                   DataSource.Add(d);
                                   TweetListBox.ItemsSource = DataSource;
                               });
                    }
                });
            }
            else
            {
                BlogListBox.Visibility = Visibility.Visible;
                DataItems d = new DataItems();
               d.item=(SyndicationItem)Constants.SelectedSyndicationItem[0];
               DataSource.Add(d);
               BlogListBox.ItemsSource = DataSource;
               
            }
        }

        private void btnPost_Click(object sender, RoutedEventArgs e)
        {
            string PostId = string.Empty;
            var fb = new FacebookClient(AppSettings.FaceBookAccessToken);
            string Link =((SyndicationItem)DataSource[0].item).Links.FirstOrDefault().Uri.ToString();

            if (!Link.Contains("fbid="))
            {
                PostId = Link.Substring(Link.LastIndexOf('/') + 1);
            }
            else
            {
                PostId = Link.Substring(Link.IndexOf('=') + 1, ((Link.IndexOf('&') - 1) - Link.IndexOf('=')));
            }
                fb.PostCompleted += (o, args) =>
                {
                    if (args.Error != null)
                    {
                        Dispatcher.BeginInvoke(() => MessageBox.Show(args.Error.Message));
                        return;
                    }
                    var result = (IDictionary<string, object>)args.GetResultData();
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Comment Posted successfully");
                        (CommentBox as TextBox).Text = string.Empty;

                    });
                };

                var parameters = new Dictionary<string, object>();
                parameters["message"] = (CommentBox as TextBox).Text;

                fb.PostAsync("/" + PostId + "/comments", parameters);
            
        }

        private void btnPost1_Click(object sender, RoutedEventArgs e)
        {
            TwitterLoginPage p = new TwitterLoginPage();
            var service = new TwitterService("LYTy3T8P556GxqRymimhwA", "5TSKipEjESOAcdBsViWm2E1RVxFEN1Ooh0nRwIj7RsY");
            string[] Tokens = new string[2];
            Tokens = p.ReturnTokens(p.getAccessToken());
            service.AuthenticateWith(Tokens[0], Tokens[1]);
            service.SendTweet(new SendTweetOptions { InReplyToStatusId = ((TwitterStatus)DataSource[0].item).Id, Status = "@" + ((TwitterStatus)DataSource[0].item).User.ScreenName + " " + (CommentBox as PhoneTextBox).Text }, tweetResponse);
        }
        private void tweetResponse(TwitterStatus tweet, TwitterResponse response)
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Tweet posted successfully"); NavigationService.GoBack(); });
                
            }
            else
            {
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    Dispatcher.BeginInvoke(() => { MessageBox.Show("Authentication error"); NavigationService.GoBack(); });
                   
                }
                else
                {
                    Dispatcher.BeginInvoke(() => { MessageBox.Show("Error, please try again later"); NavigationService.GoBack(); });
                    
                }
            }
        }

        private void btnPost2_Click(object sender, RoutedEventArgs e)
        {
            BackgroundWorker bg = new BackgroundWorker();
            bg.DoWork += bg_DoWork;
            bg.RunWorkerCompleted += bg_RunWorkerCompleted;
            bg.RunWorkerAsync();
            BlogComment = (CommentBox as TextBox).Text;
            
        }

        void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (Constants.CommentPosted == true)
            {
                    MessageBoxResult result = MessageBox.Show("Comment Posted successfully","",MessageBoxButton.OK);
                    if (result == MessageBoxResult.OK)
                    {
                        (CommentBox as TextBox).Text = string.Empty;
                        Constants.CommentPosted = false;
                        NavigationService.GoBack();
                    }
               
            }
            else
            {
                    MessageBoxResult result = MessageBox.Show("The user does not allow to create a comment", "", MessageBoxButton.OK);
                    if (result == MessageBoxResult.OK)
                    {
                        (CommentBox as TextBox).Text = string.Empty;
                        NavigationService.GoBack();
                    }
            }
        }

        void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            string Id=((SyndicationItem)Constants.SelectedSyndicationItem[0]).Id;
            PostToblog p = new PostToblog();
            p.UploadItem(BlogComment, auto, Id.Substring(Id.IndexOf('-') + 1, (Id.LastIndexOf('.') - (Id.IndexOf('-') + 1))), Id.Substring(Id.LastIndexOf('-') + 1));
            auto.WaitOne();
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            if (FeedType == "FaceBook")
            {
                btnPost_Click(null, null);
            }
            else if (FeedType == "Twitter")
            {
                btnPost1_Click(null, null);
            }
            else
            {
                btnPost2_Click(null, null);
            }
        }

        private void txtComment_Loaded(object sender, RoutedEventArgs e)
        {
            CommentBox = sender as TextBox;
        }

        private void txtComment1_Loaded(object sender, RoutedEventArgs e)
        {
            (sender as PhoneTextBox).Hint = "@" +((TwitterStatus)DataSource[0].item).User.ScreenName + " ";
            CommentBox = sender as PhoneTextBox;
            
        }

        private void txtComment2_Loaded(object sender, RoutedEventArgs e)
        {
            CommentBox = sender as TextBox;
        }

        private void Image_ImageOpened(object sender, RoutedEventArgs e)
        {
            if((sender as Image).RenderSize.Height<100)
            {
                (sender as Image).Visibility = Visibility.Collapsed;
            }
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            (sender as Image).Visibility = Visibility.Collapsed;
        }
    }
}